package com.zzyl.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.google.common.collect.Lists;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.service.CustomerUserService;
import com.zzyl.service.WeCatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class CustomerUserServiceImpl implements CustomerUserService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    WeCatService weCatService;

    static ArrayList<String> DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //loginvo 有2个数据需要返回，一个是微信昵称，一个是token
        // 1. 通过微信code获取openid（hutool）
        // todo 使用hutool工具包发起网络请求（接口来自，微信官网）
        String openId = weCatService.getOpenId(userLoginRequestDto.getCode());
        // 2. 通过微信phoneCode获取phone（hutool）
        String phone =weCatService.getPhone(userLoginRequestDto.getPhoneCode());
        // 3. openid去查询后数据库，
      Member member= memberMapper.selectByOpenId(openId);
        // 4. 如果没有，则创建用户，返回token
        if (member == null) {
            // 创建用户
             member = new Member();
            member.setOpenId(openId);
            //ember.setPhone(phone);
            // 手机号码和微信的opneid 并不是绑死的，可以解绑，也就是说微信可以换不同的手机号码
        }
        //到此，member一定是有值的
        saveOrUpdate(member,phone);

        //将member 转成token
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(member.getName());
        Map<String,Object> map = new HashMap<>();
        map.put("username",member.getName());
        map.put("id",member.getId());
        String token = JwtUtil.createJWT("itheima", 600000, map);
        loginVo.setToken(token);
        return loginVo;
    }

    private void saveOrUpdate(Member member, String phone) {

        //1. 判断手机号码是和数据库种一样，如果不一样，就重新设置
        if (ObjectUtil.notEqual(phone,member.getPhone())){
            member.setPhone(phone);
        }

        //2. 判断id是否存在
        if (member.getId() == null){
            //不存在，则新增
            String nickName = DEFAULT_NICKNAME_PREFIX.get(RandomUtil.randomInt(DEFAULT_NICKNAME_PREFIX.size()))
                    + StringUtils.substring(member.getPhone(), 7, 11);
            member.setName(nickName);
            member.setGender(1);
            memberMapper.insert(member);
        }else {
            //存在，则更新
            memberMapper.updateById(member);
        }


    }
}
